<template>
  <div class="bookdetail-container">
    <!-- 图书图片轮播图 -->
    <div class="carousel-block">
      <span class="demonstration">书籍图片</span>
      <el-carousel :interval="4000" type="card" height="350px">
        <el-carousel-item v-for="(item,index ) in bookImgs" :key="index">
          <el-image :src="item.imgName" fit="scale-down" style="height:100%">
            <div slot="placeholder" class="image-slot">
              加载中
              <span class="dot">...</span>
            </div>
          </el-image>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 图书基本信息展示 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>详细信息</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="showUpdateDialog">信息修改</el-button>
        <!-- <el-button style="float: right; padding: 3px 0" type="text">||</el-button> -->
        <el-button
          style="float: right; padding: 3px 0;margin-right:20px"
          type="text"
          @click="showUpdateImgDialog"
        >图片修改</el-button>
      </div>

      <div class="base-message">
        <el-row>
          <el-col :span="12">
            <div class="grid-content bg-purple">id：{{ bookDetail.id }}</div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple-light">书名：{{ bookDetail.bookName }}</div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="grid-content bg-purple">作者：{{ bookDetail.author }}</div>
          </el-col>
          <el-col :span="12">
            <div
              class="grid-content bg-purple-light"
            >出版社：{{ bookDetail.publisher?bookDetail.publisher:'未知' }}</div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="grid-content bg-purple">价格：{{ bookDetail.price }}</div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple-light">库存：{{ bookDetail.repositoryNum }}</div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="grid-content bg-purple">销量：{{ bookDetail.sales }}</div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple-light">
              类别：
              <span
                v-for="(item,index) in bookDetail.categories"
                :key="index"
              >{{ item.name+' ' }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="book-des">
        <span>图书描述：</span>
        <el-row>
          <el-col :span="24">
            <p>{{ bookDetail.bookDes }}</p>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 图书信息修改框 -->
    <el-dialog title="图书修改" :visible.sync="dialogVisible" :before-close="handleBeforeClose">
      <el-form ref="updateFrom" :model="updateFrom" label-position="top" :rules="updateFromRules">
        <el-row>
          <el-col :span="11">
            <el-form-item label="书名" :label-width="formLableWidth" prop="bookName">
              <el-input v-model="updateFrom.bookName" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="2">
            <el-form-item label="作者" :label-width="formLableWidth" prop="author">
              <el-input v-model="updateFrom.author" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="出版社" :label-width="formLableWidth">
              <el-input v-model="updateFrom.publisher" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="2">
            <el-form-item label="价格" :label-width="formLableWidth" prop="price">
              <el-input v-model="updateFrom.price" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="库存" :label-width="formLableWidth" prop="repositoryNum">
              <el-input v-model.number="updateFrom.repositoryNum" autocomplete="off" type="number" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="图书类别" :label-width="formLableWidth" prop="categories">
              <el-select v-model="updateFrom.categories" multiple>
                <el-option
                  v-for="(item) in categoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row type="flex">
          <el-col :span="24">
            <el-form-item label="描述" :label-width="formLableWidth">
              <el-input v-model="updateFrom.bookDes" type="textarea" :rows="5" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancelUpdate">取  消</el-button>
        <el-button type="primary" @click="handleUpdateCommit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 图书图片修改框 -->
    <el-dialog title="图片修改" :visible.sync="imgDialog" style="height:100%">
      <div>
        <!-- 图片删除 -->
        <div v-if="bookImgs.length > 0" class="pic-del">
          <el-button type="danger" @click="delImgs">删除</el-button>
          <div style="margin: 15px 0;" />
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;" />
          <el-row>
            <el-checkbox-group v-model="checkedImgIds" @change="handleCheckedImgChange">
              <el-col v-for="item in bookImgs" :key="item.id" :span="6">
                <el-checkbox :label="item.id">
                  <div class="block">
                    <el-image
                      style="width: 100px; height: 100px"
                      :src="item.imgName"
                      fit="fit"
                      :preview-src-list="bookImgNames"
                    />
                  </div>
                </el-checkbox>

              </el-col>
            </el-checkbox-group>
          </el-row>
        </div>
        <!-- 图片添加 -->
        <div class="upload-pic">
          <div style="margin: 45px 0;" />
          <el-row>
            <el-col :span="24">
              <el-form label-position="top">
                <el-form-item label="图片添加">
                  <el-upload
                    ref="upload"
                    action="#"
                    list-type="picture-card"
                    :auto-upload="false"
                    :limit="4"
                    :multiple="true"
                    :on-exceed="handleOver"
                    :before-upload="beforeAvatarUpload"
                    :file-list="fileList"
                    :on-change="handleChange"
                    :data="client"
                    :http-request="doUpload"
                    :on-error="handleError"
                    :on-success="success"
                  >
                    <i slot="default" class="el-icon-plus" />
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
                    <div slot="file" slot-scope="{file}">
                      <img class="el-upload-list__item-thumbnail" :src="file.url">
                      <span class="el-upload-list__item-actions">
                        <span
                          class="el-upload-list__item-preview"
                          @click="handlePictureCardPreview(file)"
                        >
                          <i class="el-icon-zoom-in" />
                        </span>
                        <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                          <i class="el-icon-delete" />
                        </span>
                      </span>
                    </div>
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt>
                  </el-dialog>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="upload">上传</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>

        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getBookDetailById, getCategory, updateBook, delBookImgs, addBookImgNames } from '@/utils/book.js'
import { getClient, getFileNameUUID } from '@/api/upload'

export default {
  data() {
    const validateRep = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('请输入库存'))
      }
      if (value === 0 || value < 0) {
        return callback(new Error('库存数量应该大于0'))
      } else {
        if (parseInt(value, 10) === value) {
          return callback()
        } else {
          return callback(new Error('库存数量不能有小数'))
        }
      }
    }
    const validatePrice = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('请输入价格'))
      }
      if (value === 0 || value < 0 || value === '0') {
        return callback(new Error('价格应该大于0'))
      } else {
        return callback()
      }
    }
    return {
      // 图书图片删除相关-------------------
      checkedImgIds: [],
      bookImgsIds: [],
      // 图片全选
      checkAll: false,
      isIndeterminate: false,
      imgDialog: false,
      // 图书图片删除相关------------------
      // 图书图片上传相关------------------
      fileList: [],
      imgNames: [],
      client: getClient(),
      dialogImageUrl: '',
      // 图书图片上传相关------------------
      currentBookId: '',
      bookDetail: {
        id: '',
        bookName: '',
        author: '',
        publisher: '',
        price: '',
        repositoryNum: '',
        bookDes: '',
        // 修改后的图书类别id
        categories: [],
        bookImgs: []
      },
      bookImgs: [],
      bookImgNames: [],

      formLableWidth: '120px',
      // categoryList: [],
      getCategoryForm: {
        current: 1,
        size: 99,
        orderType: 0
      },

      // 更新图书基本信息相关------------------
      // 更新的对象
      dialogVisible: false,
      updateFrom: {
        id: '',
        bookName: '',
        author: '',
        publisher: '',
        price: '',
        repositoryNum: '',
        bookDes: '',
        // 修改后的图书类别id
        categories: []
      },
      updateFromRules: {
        bookName: [{ required: true, trigger: 'blur', message: '请输入图书名称' }],
        author: [{ required: true, trigger: 'blur', message: '请输入图书作者' }],
        price: [{ required: true, trigger: 'change', validator: validatePrice }],
        repositoryNum: [{ type: 'number', required: true, trigger: 'change', validator: validateRep }],
        categories: [{ required: true, message: '请选择图书类别', trigger: 'blur' }]
      }
      // 更新图书基本信息相关------------------
    }
  },
  computed: {
    // 所有图书类别数组
    categoryList() {
      return this.$store.getters.categoryList
    }
  },
  created() {
    this.getCategaryList()
    this.getBook()
  },
  methods: {
    // 文件列表删除
    handleRemove(file) {
      const arr = this.fileList.filter(element => {
        return element.uid !== file.uid
      })
      this.fileList = arr
    },

    // 文件预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 文件数量超出限制
    handleOver(file, fileList) {
      this.$message.error('最多上传4个图片')
    },

    // 点击上传按钮
    upload() {
      if (this.fileList && this.fileList.length > 0) {
        this.$refs.upload.submit()
      } else {
        this.$message.error('请添加图书图片')
      }
    },

    handleError(err, file, fileList) {
      console.log(err)
    },
    // 进行图片的后缀验证
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或者 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleChange(file, fileList) {
      this.fileList = fileList
    },
    doUpload(file) {
      // console.log(file)
      try {
        const fileName = getFileNameUUID() + file.file.name
        this.client.put(fileName, file.file).then(res => {
          // console.log('成功了')
          // 每一张图片上传成功保留imgName
          // console.log();
          this.imgNames.push(fileName)
          if (this.imgNames.length === this.fileList.length) {
            // // 图片上传成功，进行添加图书
            // 图书imgName插入数据库
            console.log(this.imgNames.length)
            console.log(this.fileList.length)
            this.doAddBookImgNames(this.imgNames)
          }
        }).catch(() => {
          this.$notify.error({
            title: '错误',
            message: '添加图书失败'
          })
          this.fileList = []
          this.imgNames = []
        })
      } catch (e) {
        console.log(e)
        this.fileList = []
        this.imgNames = []
      }
    },
    doAddBookImgNames(imgNames) {
      // 构造bookQo，
      // console.log(imgNames)
      const arr = []
      imgNames.forEach(element => {
        const obj = {
          imgName: element
        }
        arr.push(obj)
      })
      // console.log(arr)
      addBookImgNames(this.$route.params.id, arr).then(res => {
        this.$notify({
          title: '成功',
          message: '添加成功',
          type: 'success'
        })
        // 数据清理
        this.getBook()
        this.imgDialog = false
        this.fileList = []
        this.imgNames = []
      }).catch(() => {
        this.fileList = []
        this.imgNames = []
      })
    },
    success() {
      this.$message('成功了')
    },
    delImgs() {
      if (this.checkedImgIds.length === 0) {
        this.$message('请选择图片')
      } else {
        // console.log(this.checkedImgIds)
        delBookImgs(this.$route.params.id, this.checkedImgIds).then(res => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success'
          })
          this.imgDialog = false
          // 数据清理
          this.getBook()
        }).catch()
      }
    },
    handleCheckAllChange(val) {
      this.checkedImgIds = val ? this.bookImgsIds : []
      this.isIndeterminate = false
    },
    handleCheckedImgChange(val) {
      // console.log(val)
      const checkedCount = val.length
      this.checkAll = checkedCount === this.bookImgsIds.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.bookImgsIds.length
    },
    handleDownload() {

    },
    // 获取图书类别
    getCategaryList() {
      if (this.categoryList && this.categoryList.length > 0) {
        // console.log('具有categories');
      } else {
        getCategory(this.getCategoryForm).then(res => {
          this.$store.commit('book/SET_CATEGORYLIST', res.object.records)
        })
      }
    },
    // 从地址栏获取图书id，向后端请求图书信息
    async getBook() {
      this.currentBookId = this.$route.params.id
      // console.log(this.currentBookId)
      await this.getBoodById(this.currentBookId)
    },
    getBoodById(id) {
      getBookDetailById(id).then(res => {
        // console.log(res.object)
        this.bookDetail = res.object
        this.bookImgs = this.bookDetail.bookImgs
        const arr = []
        const arrb = []
        this.bookImgs.forEach(element => {
          arr.push(element.imgName)
          arrb.push(element.id)
        })
        this.bookImgNames = arr
        this.bookImgsIds = arrb
        this.setUpdateForm()
      })
    },
    setUpdateForm() {
      const arr = []
      const cateList = this.bookDetail.categories
      cateList.forEach(e => {
        arr.push(e.id)
      })
      this.updateFrom.categories = arr
      this.updateFrom.id = this.bookDetail.id
      this.updateFrom.bookName = this.bookDetail.bookName
      this.updateFrom.author = this.bookDetail.author
      this.updateFrom.price = this.bookDetail.price
      this.updateFrom.repositoryNum = this.bookDetail.repositoryNum
      this.updateFrom.publisher = this.bookDetail.publisher
      this.updateFrom.bookDes = this.bookDetail.bookDes
    },

    // 显示图书update 框
    showUpdateDialog() {
      this.dialogVisible = true
    },
    showUpdateImgDialog() {
      this.imgDialog = true
    },
    // 取消更新
    handleCancelUpdate() {
      this.dialogVisible = false
      this.fileList = []
      this.imgNames = []
    },
    // 提交更新
    handleUpdateCommit() {
      this.$refs.updateFrom.validate((valid) => {
        if (valid) {
          // console.log('成功')
          // 1.修改categories
          const arr = []
          this.updateFrom.categories.forEach(element => {
            arr.push({ id: element })
          })
          this.updateFrom.categories = arr
          this.doUpdate()
        } else {
          return false
        }
      })
    },
    doUpdate() {
      updateBook(this.updateFrom).then(res => {
        this.$message.success('更新图书成功')
        this.dialogVisible = false
        this.getBook()
      }).catch(error => {
        this.$message.success(error)
      })
    },
    // 关闭之前的钩子
    handleBeforeClose() {
      // console.log('关闭llll')
      // 表单重置
      // this.$refs.updateFrom.resetFields()
      this.dialogVisible = false
      this.fileList = []
      this.imgNames = []
      this.setUpdateForm()
    }
  }

}
</script>

<style scoped lang='scss'>
.bookdetail-container {
  margin: 20px 200px;
}
// .carousel-block {
//   text-align: center;
// }
.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
}

.el-carousel__item {
  text-align: center;
}

.box-card {
  margin-top: 20px;
}

.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
// .bg-purple {
//   background: #d3dce6;
// }
// .bg-purple-light {
//   background: #e5e9f2;
// }
.grid-content {
  border-radius: 4px;
  min-height: 20px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
.base-message {
  box-sizing: border-box;
  padding-bottom: 20px;
  border-bottom: 1px solid #e6ebf5;
}
.book-des {
  margin-top: 20px;
}

.el-form {
  border-top: 1px solid #e6ebf5;
  padding-top: 10px;
}

.el-select {
  width: 100% !important;
}
</style>
